//
//  ListenSingleCategoryViewController.m
//  JianChaRiBao
//
//  Created by yuzhou on 13-5-28.
//  Copyright (c) 2013年 wzyk. All rights reserved.
//

#import "ListenSingleCategoryViewController.h"
#import "ListenCell.h"
#import "ListenInfoViewController.h"
#import "AppDelegate.h"
#import "ListenShelfViewController.h"
#import "SearchViewController.h"

@interface ListenSingleCategoryViewController ()
@property (nonatomic,retain) NSArray *listenArray;
@end

@implementation ListenSingleCategoryViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePlayerBar) name:kPlayerStateDidChange object:nil];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    categoryGridView.leftContentInset = 20;
    categoryGridView.rightContentInset = 20;
    categoryGridView.contentInset = UIEdgeInsetsMake(0, 0, 1, 0);
    categoryGridView.backgroundViewExtendsDown = YES;
    UIView *bgView = [[UIView alloc] init];
    bgView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bookshelf_cell_bg"]];
    categoryGridView.backgroundView = bgView;
    if (_category) {
        [self getData];
        nameLabel.text = [_category objectForKey:@"class_name"];
    }
    [self updatePlayerBar];
}

- (void)setCategory:(NSDictionary *)category
{
    if (category && ![category isEqualToDictionary:_category]) {
        [_category release];
        _category = [category retain];
        if ([self isViewLoaded]) {
            [self resetDisplay];
            [self getData];
        }
    }
}
- (void)showLoadingView
{
    if (loadingView.superview) {
        return;
    }
    if (loadingView == nil) {
        loadingView = [[[ABSpringLoadingView alloc] initWithFrame:categoryGridView.frame] autorelease];
    }
    loadingView.alpha = 0;
    [self.view addSubview:loadingView];
    [UIView animateWithDuration:0.3 animations:^{
        loadingView.alpha = 1;
    }];
}

- (void)removeloadingView
{
    if (loadingView) {
        [UIView animateWithDuration:0.3 animations:^{
            loadingView.alpha = 0;
        } completion:^(BOOL finished) {
            [loadingView removeFromSuperview];
            loadingView = nil;
        }];
    }
}

- (void)getData
{
    [self showLoadingView];
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSDictionary *data = [[DataRequest sharedRequest] getListenByCatgory:[_category objectForKey:@"class_id"]];
        dispatch_async(dispatch_get_main_queue(), ^{
            [self removeloadingView];
            if (data && [data isKindOfClass:[NSDictionary class]] && [[data objectForKey:@"result"] isKindOfClass:[NSArray class]]) {
                self.listenArray = [data objectForKey:@"result"];
                [categoryGridView reloadData];
            }
        });
    });
}

- (void)resetDisplay
{
    self.listenArray = nil;
    [categoryGridView reloadData];
    nameLabel.text = [_category objectForKey:@"class_name"];
}

- (NSUInteger)numberOfItemsInGridView:(AQGridView *)gridView
{
    return _listenArray.count;
}

- (AQGridViewCell *)gridView:(AQGridView *)gridView cellForItemAtIndex:(NSUInteger)index
{
    static NSString *CellIdentify = @"ListenCell";
    ListenCell *cell = (ListenCell *)[gridView dequeueReusableCellWithIdentifier:CellIdentify];
    if (cell == nil) {
        cell = [[ListenCell alloc] initWithFrame:CGRectMake(0, 0, 70, 100) reuseIdentifier:CellIdentify];
    }
    cell.listenInfo = [_listenArray objectAtIndex:index];
    [cell updateDisplay];
    return cell;
}

- (CGSize)portraitGridCellSizeForGridView:(AQGridView *)gridView
{
    return CGSizeMake(80, 150);
}

- (CGRect)gridView:(AQGridView *)gridView adjustCellFrame:(CGRect)cellFrame withinGridCellFrame:(CGRect)gridCellFrame
{
    cellFrame.origin.y -= 5;
    return cellFrame;
}

- (void)gridView:(AQGridView *)gridView didSelectItemAtIndex:(NSUInteger)index
{
    ListenInfoViewController *listenInfoViewController = [[[ListenInfoViewController alloc] initWithNibName:@"ListenInfoViewController" bundle:nil] autorelease];
    listenInfoViewController.listenID = [[_listenArray objectAtIndex:index] objectForKey:@"item_id"];
    listenInfoViewController.listenName = [[_listenArray objectAtIndex:index] objectForKey:@"item_name"];
    [[UIApplication rootNavController] pushViewController:listenInfoViewController animated:YES];
    [gridView deselectItemAtIndex:index animated:NO];
}

- (IBAction)showCategory
{
    [[UIApplication rootViewController] showWidgetView];
}

- (IBAction)showShelf:(id)sender {
    ListenShelfViewController *listenShelfViewController = [[[ListenShelfViewController alloc] initWithNibName:@"ListenShelfViewController" bundle:nil] autorelease];
    [[UIApplication rootNavController] pushViewController:listenShelfViewController animated:YES];
}

- (IBAction)searchBtnClicked:(id)sender {
    SearchViewController * searchViewController = [[[SearchViewController alloc]initWithNibName:@"SearchViewController" bundle:nil]autorelease];
    searchViewController.type = searchListen;
    [[UIApplication rootNavController] pushViewController:searchViewController animated:YES];
}

- (void)swipeBack
{
    [self showCategory];
}

- (void)updatePlayerBar {
    // 判断是否正在播放
    if ([CollectionData hasContent:kCollection_playing]) {
        if (playerBarView) {
            return;
        }
        
        playerBarView = [[[NSBundle mainBundle] loadNibNamed:@"PlayerBarView" owner:self options:nil] objectAtIndex:0];
        CGRect frameTable = categoryGridView.frame;
        CGRect frameBar = playerBarView.frame;
        frameBar.origin.x = frameTable.origin.x;
        frameBar.origin.y = frameTable.origin.y;
        playerBarView.frame = frameBar;
        [self.view addSubview:playerBarView];
        
        frameTable.origin.y += PlayerBarHeight;
        frameTable.size.height -= PlayerBarHeight;
        categoryGridView.frame = frameTable;
    }
    else if (playerBarView) {
        [playerBarView removeFromSuperview];
        playerBarView = nil;
        
        CGRect frameTable = categoryGridView.frame;
        frameTable.origin.y -= PlayerBarHeight;
        frameTable.size.height += PlayerBarHeight;
        categoryGridView.frame = frameTable;
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [nameLabel release];
    [categoryGridView release];
    [_category release];
    [_listenArray release];
    [super dealloc];
}
- (void)viewDidUnload {
    [nameLabel release];
    nameLabel = nil;
    [categoryGridView release];
    categoryGridView = nil;
    [super viewDidUnload];
}
@end
